#include "File.h"
#include "Game.h"
#include "Timeline.h"
#include "Factory.h"
#include "ReportError.h"
#include "Timer.h"

Timeline::Timeline()
{
	
}

void Timeline::AddTLK(float time, TimelineKey* tlk)
{
	m_keys.insert( std::pair<float, TimelineKey*>  (time,tlk));

}

void Timeline::Update()
{
	

	//Update elapsed time
	m_elapsedTime += TheTimer::Instance()->GetDT();
	
	// check which TLKs need to be triggered
	while(m_it != m_keys.end())
	{
		if(m_elapsedTime <= (*m_it).first)
		{
			break;
		}
		else 
		{
			(*m_it).second->Execute();
			++m_it;
		}
		
	}

}

void Timeline::Reset()
{
	m_elapsedTime = 0;
	m_it = m_keys.begin();
}

bool Timeline::Load(const std::string& filename) 
{
	File f;

	if (!f.OpenRead(filename))
	{
		ReportError("Cannot Open File: " + filename );
		return false;
	}

	std::string line;
	while(1)
	{
		//float absTime = (float)atof(line.c_str());
		float absTime = 0;
		if(!f.GetFloat(&absTime))
		{
			break;
			//ReportError("TLK absTime");
			
		}
		//Create tlk from string
		std::string s;
		if (!f.GetString(&s))
		{
			ReportError("Expected a time line key at: " + __LINE__);
			return false;
		}
		
		TimelineKey* k = TheTLKFactory::Instance()->Create(s);

		if(!k->Load(&f))
		{
			ReportError("TimelineKey load function returned false at: " + __LINE__);
		}
		
		m_keys.insert(std::make_pair(absTime, k));
	}
	Reset();
	return true;
}